#!/bin/sh

#
# Test error
#
# Copyright 2022 Odin Kroeger.
#
# This file is part of suCGI.
#
# suCGI is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# suCGI is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General
# Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with suCGI. If not, see <https://www.gnu.org/licenses/>.
#

#
# Initialiation
#

set -Cefu
scriptsdir="$(cd -P "$(dirname -- "$0")" && pwd)"
: "${scriptsdir:?}"
readonly scriptsdir
: "${srcdir:="${SRCDIR-}"}"
: "${srcdir:="$(cd -P "$scriptsdir/.." && pwd)"}"
: "${srcdir:?}"
readonly srcdir

# shellcheck disable=2154
export PATH="$scriptsdir/bin:$PATH"

# shellcheck disable=1091
. "$srcdir/libutil.sh"	|| exit
init			|| exit
# shellcheck disable=2119
tmpdir			|| exit

# Always exit with a status indicating failure unless $fin is set
atexit="${atexit-:}; [ \"\${fin-}\" ] || exit 69"


#
# Globals
#

# Test result
result=0


#
# Options
#

OPTIND=1 OPTARG='' opt=''
while getopts dh opt
do
	# shellcheck disable=2154
	case $opt in
	(h) exec cat <<EOF ;;
$progname - test error

Usage:  $progname [-d]
        $progname -h

Options:
    -d  Enable debugging mode.
    -h  Show this help screen.
EOF
	(d) set -x ;;
	(*) exit 2
	esac
done
shift $((OPTIND - 1))
unset opt


#
# Build configuration
#

eval "$(sucgi -c | grep -E ^NDEBUG=)"


#
# Assertions
#

if ! [ "${NDEBUG-}" ]
then
	# The Korn shell handles signals differently
	case ${KSH_VERSION-} in
	(''|*PD*|*MIR*) retval=134 ;;
	(*)             retval=262 ;;
	esac

	trap : ABRT
	check -s"$retval" -e"*message" error ''
	trap - ABRT
fi


#
# Messages
#

for format in - foo bar baz %s foo%s bar%s baz%s
do
	for arg in - foo bar baz
	do
		case $format in
		(*%s*)	# shellcheck disable=2059
			message="$(printf -- "$format" "$arg")" ;;
		(*)	# shellcheck disable=2059
			message="$(printf -- "$format")" ;;
		esac
		check -s1 -e"$message" error "$format" "$arg" || result=70
	done
done


#
# Result
#

# shellcheck disable=2034
fin=y
exit "$result"
